package com.dycn.posdashboard.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.batik.transcoder.TranscoderException;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.ImageTranscoder;
import org.apache.batik.transcoder.image.JPEGTranscoder;
import org.apache.batik.transcoder.image.PNGTranscoder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;

import com.dycn.posdashboard.data.JsonResponseData;
import com.dycn.posdashboard.listener.SystemInitListener;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class ClientSVGImageExportAction extends ActionSupport {
    protected final Log log = LogFactory.getLog(getClass());
	

    public static final java.lang.String ERROR = "error";
    /**
	 * 
	 */
	private static final long serialVersionUID = -1075965353986659584L;

	private String contentType;
    private JsonResponseData<Object> commonResponseDataJson;
    private String                msg;
	
	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public JsonResponseData<Object> getCommonResponseDataJson() {
		return commonResponseDataJson;
	}

	public void setCommonResponseDataJson(
			JsonResponseData<Object> commonResponseDataJson) {
		this.commonResponseDataJson = commonResponseDataJson;
	}

	public void setContentType(String contentType) {
		this.contentType = contentType;
	}

	private String fileName;

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	private InputStream inputStream;


	public InputStream getInputStream() {
		return inputStream;
	}

	public void setInputStream(InputStream inputStream) {
		this.inputStream = inputStream;
	}

	public String chartExportAsSVG(){
		commonResponseDataJson=new JsonResponseData<Object>();
		commonResponseDataJson.setSuccess(false);
		commonResponseDataJson.setResultCode(JsonResponseData.SUCCESS);
		commonResponseDataJson.setMsg("参数提交错误~~~!!!!!!");
		commonResponseDataJson.setData(null);
		
		HttpServletRequest request = ServletActionContext.getRequest();
		String contentType = "image/png";//image/jpeg
		String svgString = request.getParameter("svg");
		String width=request.getParameter("width");
		String height=request.getParameter("height");
		String svgName=request.getParameter("svgName");
		String rootFolder = SystemInitListener.ROOT_FOLDER;
		fileName = svgName+"_"+new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+"_svg_"+ "."
				+ contentType.substring(6);
		try {
			//File.pathSeparator指的是分隔连续多个路径字符串的分隔符
			//File.separator才是用来分隔同一个路径字符串中的目录的
			File f = new File(rootFolder + File.separator + fileName);

			ImageTranscoder trans=null;
			TranscoderInput input=null;
			if(contentType.substring(6).equals("png")){
				trans = new PNGTranscoder();
				//trans.addTranscodingHint(PNGTranscoder.k, new Float(.8));
				trans.addTranscodingHint( PNGTranscoder.KEY_PIXEL_UNIT_TO_MILLIMETER, new Float( 0.264583));
	            trans.addTranscodingHint( PNGTranscoder.KEY_WIDTH, new Float( width ));
	            trans.addTranscodingHint( PNGTranscoder.KEY_HEIGHT, new Float(height)); 
				input = new TranscoderInput(new StringReader(
						svgString));
			}else{
				trans = new JPEGTranscoder();
				trans.addTranscodingHint(JPEGTranscoder.KEY_QUALITY, new Float(.8));
	            trans.addTranscodingHint( JPEGTranscoder.KEY_WIDTH, new Float( width ));
	            trans.addTranscodingHint( JPEGTranscoder.KEY_HEIGHT, new Float(height)); 
				input = new TranscoderInput(new StringReader(
						svgString));
			}
			
			OutputStream ostream = new FileOutputStream(f);
			TranscoderOutput output = new TranscoderOutput(ostream);
			// Save the image.
			trans.transcode(input, output);
			// Flush and close the stream.
			ostream.flush();
			ostream.close();

			commonResponseDataJson.setMsg("");
    		commonResponseDataJson.setSuccess(true);
    		commonResponseDataJson.setResultCode(JsonResponseData.SUCCESS);
    		commonResponseDataJson.setData(fileName);

	
		} catch (FileNotFoundException exp) {
			exp.printStackTrace();
    		commonResponseDataJson.setResultCode(JsonResponseData.EXCEPTION);
    		commonResponseDataJson.setMsg(commonResponseDataJson.getMsg()+exp);
		} catch (IOException exp) {
			// TODO Auto-generated catch block
			exp.printStackTrace();
    		commonResponseDataJson.setResultCode(JsonResponseData.EXCEPTION);
    		commonResponseDataJson.setMsg(commonResponseDataJson.getMsg()+exp);
		} catch (TranscoderException exp) {
			// TODO Auto-generated catch block
			exp.printStackTrace();
    		commonResponseDataJson.setResultCode(JsonResponseData.EXCEPTION);
    		commonResponseDataJson.setMsg(commonResponseDataJson.getMsg()+exp);
		}catch (Exception exp) {
			// TODO Auto-generated catch block
			exp.printStackTrace();
    		commonResponseDataJson.setResultCode(JsonResponseData.EXCEPTION);
    		commonResponseDataJson.setMsg(commonResponseDataJson.getMsg()+exp);
		}

		return SUCCESS;
	}
	
	public String downloadFile() {
		String rootFolder = SystemInitListener.ROOT_FOLDER;
		HttpServletRequest request = ServletActionContext.getRequest();
		fileName = request.getParameter("file");
        try {

        	fileName=new String(fileName.getBytes("ISO8859-1"), "UTF-8");
			log.debug("downloadFile tmp:::"+fileName);
			//log.debug("required fileName2:::"+java.net.URLEncoder.encode(fileName, "UTF-8"));
			//gz file name

			File f = new File(rootFolder+File.separator+fileName);

	        System.out.println("downloadFile:::"+f.getAbsolutePath());
	        if (f.exists())
	        {
	            try {
	                inputStream = new FileInputStream(f);
//	                int fileSize=0;
//	                try{
//	                	fileSize=inputStream.available();
//	                
//	                }catch(Exception exp){
//	                	
//	                }
	            } catch (FileNotFoundException e) {
	                throw e;
	            }
	        }
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			
			commonResponseDataJson=new JsonResponseData<Object>();
			commonResponseDataJson.setSuccess(false);
			commonResponseDataJson.setResultCode(JsonResponseData.NOT_FOUND);
			commonResponseDataJson.setMsg("指定文件无法下载,可能已经不存在或被移动到其他目录~~!!!!!!");
			commonResponseDataJson.setData("");
			this.setMsg(JsonResponseData.NOT_FOUND);
			return ERROR;
		}
        return SUCCESS;
    }
	
	public String clientSvgExportAsImage() {
		HttpServletRequest request = ServletActionContext.getRequest();
		String contentType = request.getParameter("type");
		String svgString = request.getParameter("svg");
		String width=request.getParameter("width");
		String height=request.getParameter("height");
		String rootFolder = SystemInitListener.ROOT_FOLDER;
		fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+"_svg_"+ "."
				+ contentType.substring(6);
		try {
			//File.pathSeparator指的是分隔连续多个路径字符串的分隔符
			//File.separator才是用来分隔同一个路径字符串中的目录的
			File f = new File(rootFolder + File.separator + fileName);

			ImageTranscoder trans=null;
			TranscoderInput input=null;
			if(contentType.substring(6).equals("png")){
				trans = new PNGTranscoder();
				//trans.addTranscodingHint(PNGTranscoder.k, new Float(.8));
				trans.addTranscodingHint( PNGTranscoder.KEY_PIXEL_UNIT_TO_MILLIMETER, new Float( 0.264583));
	            trans.addTranscodingHint( PNGTranscoder.KEY_WIDTH, new Float( width ));
	            trans.addTranscodingHint( PNGTranscoder.KEY_HEIGHT, new Float(height)); 
				input = new TranscoderInput(new StringReader(
						svgString));
			}else{
				trans = new JPEGTranscoder();
				trans.addTranscodingHint(JPEGTranscoder.KEY_QUALITY, new Float(.8));
	            trans.addTranscodingHint( JPEGTranscoder.KEY_WIDTH, new Float( width ));
	            trans.addTranscodingHint( JPEGTranscoder.KEY_HEIGHT, new Float(height)); 
				input = new TranscoderInput(new StringReader(
						svgString));
			}
			
			OutputStream ostream = new FileOutputStream(f);
			TranscoderOutput output = new TranscoderOutput(ostream);
			// Save the image.
			trans.transcode(input, output);
			// Flush and close the stream.
			ostream.flush();
			ostream.close();

			inputStream = new FileInputStream(f);
	
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (TranscoderException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return SUCCESS;
	}

	public String getContentType() {

		return this.contentType;
	}

	/** 提供转换编码后的供下载用的文件名 */

	public String getDownloadFileName() {

		String downFileName = fileName;

		try {
			// downFileName=java.net.URLEncoder.encode(fileName,"UTF-8");
			// downFileName = new String(fileName.getBytes("ISO8859-1"),
			// "UTF-8");
			// downFileName = new String(downFileName.getBytes(), "ISO8859-1");

			HttpServletRequest request = ServletActionContext.getRequest();
			String Agent = request.getHeader("User-Agent");
			if (null != Agent) {
				Agent = Agent.toLowerCase();
				if (Agent.indexOf("firefox") != -1) {
					downFileName = new String(downFileName.getBytes(),
							"ISO8859-1");
				} else if (Agent.indexOf("msie") != -1) {
					downFileName = java.net.URLEncoder.encode(downFileName,
							"UTF-8");
				} else {
					downFileName = new String(downFileName.getBytes(),
							"ISO8859-1");
				}
			} else {
				downFileName = new String(downFileName.getBytes(), "ISO8859-1");
			}

			// log.debug("fileName::"+fileName);
			// log.debug("downFileName::"+downFileName);
		} catch (UnsupportedEncodingException e) {

			e.printStackTrace();

		}

		return downFileName;

	}

}
